package com.demo.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.demo.common.BaseRes;
import com.demo.util.UploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.UUID;

@RestController
@RequestMapping("/sys/upload")
@Slf4j
public class UploadController {
 
	
	/**
	 * 上传图片
	 * @param file
	 * @param request
	 * @throws IOException
	 */
	@RequestMapping( value = "/upload")
	@ResponseBody
    public BaseRes uploadPic(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) throws IOException {
        //目前这里是写死的本地硬盘路径
        BaseRes res = new BaseRes();
        String path = "D:/img";
        log.info("path:" + path);
        //获取文件名称
        String fileName = file.getOriginalFilename();
        //获取文件名后缀
        Calendar currTime = Calendar.getInstance();
        String time = String.valueOf(currTime.get(Calendar.YEAR)) + String.valueOf((currTime.get(Calendar.MONTH) + 1));
        //获取文件名后缀
        String suffix = fileName.substring(file.getOriginalFilename().lastIndexOf("."));
        suffix = suffix.toLowerCase();
        if (suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals(".png")/* || suffix.equals(".gif")*/) {
            fileName = UUID.randomUUID().toString() + suffix;
            File targetFile = new File(path, fileName);
            if (!targetFile.getParentFile().exists()) {    //注意，判断父级路径是否存在
                targetFile.getParentFile().mkdirs();
            }
            long size = 0;
            //保存
            try {
                file.transferTo(targetFile);
                size = file.getSize();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("上传失败！");
            }
            //项目url，这里可以使用常量或者去数据字典获取相应的url前缀；
            String fileUrl = "http://localhost:8080";
            //文件获取路径
            fileUrl = fileUrl + request.getContextPath() + "/img/" + fileName;
            log.info("fileUrl:" + fileUrl);
            res.setSuccess("上传成功", fileUrl);
            return res;
        } else {
            res.setFail("图片格式有误，请上传.jpg、.png、.jpeg格式的文件");
            return res;
        }


    }
        @RequestMapping("/fileUpload")
        public String fileUpload(@RequestParam("file") MultipartFile upload) {
            System.out.println("接收到了");
            if (upload.isEmpty()) {
                System.out.println("文件为空空");
            }
            String path = "D:/upload";
            File file = new File(path);
            if(!file.exists()){
                file.mkdirs();
            }

            //获取上传文件的后缀名
            String fileType  =upload.getOriginalFilename().substring(upload.getOriginalFilename().indexOf("."));
            // 获取上传文件的名称
            //String filename = upload.getOriginalFilename();
            // 把文件的名称设置唯一值，uuid
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String filename = uuid+fileType;

            try {
                upload.transferTo(new File(path,filename));
                return path+"/"+filename;
            } catch (Exception e) {
                e.printStackTrace();
            }
           return  null;
        }



    @ResponseBody
    @RequestMapping("/upload1")
    public BaseRes upload(@RequestParam("imgFile")MultipartFile imgFile,HttpServletRequest request){
        BaseRes msg = new BaseRes();
        if (imgFile.isEmpty()) {
            // 设置错误状态码
            msg.setFail("上传失败，请选择文件");
            return msg;
        }
        // 拿到文件名
        String filename = imgFile.getOriginalFilename();
        // 存放上传图片的文件夹
        File fileDir = UploadUtils.getImgDirFile();
        // 输出文件夹绝对路径  -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径
        System.out.println(fileDir.getAbsolutePath());
        try {
            // 构建真实的文件路径
            File newFile = new File(fileDir.getAbsolutePath() + File.separator + filename);
            System.out.println(newFile.getAbsolutePath());

            // 上传图片到 -》 “绝对路径”
            imgFile.transferTo(newFile);

             msg.setSuccess("上传成功!",newFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }

}